<?php

class UserController extends MainController implements ControllerInterface {

	/**
	 * Wspolna metoda
	 *
	 */
	public function __init($param) {
				if (!$this->userLoggedIn) {
			$this->addRedirectInfo('Musisz się zalogować','error',Router::GenerateUrl('User_Index',array('User' => 'Index')),0);
			$this->AddRedirectInfo($this->T('productNewComment'), 'error', Router::GenerateUrl('default'));
			$this->SetNoRender();
			
		}
	}
	public function preDispatch($param) {
		$this->RunShared('Auth');
        $this->Run($param);
	}

	public function postDispatch($param) {
	}
	
	public function IndexAction($param) {
		// dane do tabelek i paginacji start - user_table
		$table_data = $this->getTableData('users_table',$param,array('o' => 'email', 'v' => 'malejaco', 't' => 10));
		$v = $table_data['v'] == 'malejaco'?'DESC':'ASC';
		$oTable = array(
			'first_name' => 'user.first_name',
			'last_name'	=>	'user.last_name',
			'email' => "user.email"
		);
		$o = $oTable[$table_data['o']];
		$p = isset($param['strona'])?$param['strona']:1;
		$this->smarty->assign('c',UserDAL::getResult(UserDAL::GetDalDataObj(array('count' => true))));
		//dane do tabelek i paginacji koniec - users_table
		

		$users = UserDAL::GetResult(UserDAL::GetDalDataObj(array(
			'sortBy' => "$o $v",
			'join' => array(
//				'Image' => ' LEFT JOIN mf_image ON(user.id_mf_image_group = mf_image.id_image_group)'
			),
			'limit' => (($p-1)*$table_data['t']).', '.$table_data['t'],
			'groupBy' => 'user.id_user'
		)));
		
		$this->smarty->Assign('list',$users);
	}
	
	public function AjaxCheckEmailAction($param) {
		$this->SetNoRender();

		$email = Request::GetGet('email');

		$dalData = UserDAL::GetDalDataObj();
		
		$dalData->addCondition('email', '\'' . $email . '\'', '=' , 'AND');
		$dalData->addCondition('new_email', '\'' . $email . '\'', '=' , 'OR');			

		$res = UserDAL::GetResult($dalData);
		
		header("Content-type: text/html; charset=utf-8");
		
		echo json_encode((count($res) > 0)?false:true);
		exit;
	}	
	
	public function AddUserAction($param) {
		$this->addScript('jquery.validate.js');
		$this->addScript(Router::GenerateUrl('User_ValidateAddUser',array('User' => 'ValidateAddUser')).'/?id_f=add_user');
		$errors_data = $data = array(
			'first_name' => '',
			'last_name' => '',
			'email' => '',
			'password' => ''
		);
		
		if(Request::IsPost()) {
			$data = Request::GetAllPost();
			$errors = $this->ValidateAddUserAction(array('validation_data' => $data),false);
			
			if(empty($errors)) {
				$user = new User();
				$user->setStatus($data['status']);
				$user->setActive($data['active']);
				$user->setFirstName($data['first_name']);
				$user->setLastName($data['last_name']);
				$user->setEmail($data['email']);
				$user->setPassword(UserDAL::GeneratePassword($data['password']));
				
				$id = UserDAL::Insert($user->getDalDataObj());
				
				$obj = new UserExtendedProfile();
				$obj->setIdUser($id);
				UserExtendedProfileDAL::Save($obj->getDalDataObj());
				
				
				$this->addRedirectInfo('Stworzono nowego użytkownika','ok',Router::GenerateUrl('User_Index',array('User' => 'Index')),0);
			}else{
				
				
				
				foreach($errors AS $row) {
					$data[$row['field']] = $row['value'];
					$errors_data[$row['field']] = $row['msg'];
				}
			}
			
		}
		
		$this->smarty->assign('data',$data);
		$this->smarty->assign('errors',$errors_data);
	}
	
	public function ValidateAddUserAction($param, $as_action = true) {
		if($as_action)$this->SetValidatorRender();
		$validator = new Validator(isset($param['validation_data'])?$param['validation_data']:array());
		
		$validator->IsEmpty('email','Musisz podać email');
		$validator->IsEmailAddress('email','Adres email jest niepoprawny');
		$validator->IsEmpty('password','Musisz podać hasło');

		$validator->IsValidOnline('email', 'Podany email jest już zarejestrowany', Router::GenerateUrl('ajaxCheckEmail', array('User'=>'AjaxCheckEmail')));

		$this->smarty->assign('js_values',$validator->getJsValues());
		$this->smarty->assign('id_form',Request::GetGet('id_f'));
		return $validator->getErrorList();
	}
	
	public function AjaxCheckLoginAction($param) {
		$this->setAjaxRender();
		$this->partialTemplate = 'clean.tpl';
		
		$login = Request::GetGet('login');
		$count = UserDAL::GetResult(UserDAL::GetDalDataObj(array(
			'condition' => array(
				'login' => $login
			),
			'count' => true
		)));
		
		if($count == 0)$this->content= 'true';
		else $this->content= 'false';
		
	}
	
//	public function AjaxCheckEmailAction($param) {
//		$this->setAjaxRender();
//		$this->partialTemplate = 'clean.tpl';
//		
//		$email = Request::GetGet('email');
//		$count = UserDAL::GetResult(UserDAL::GetDalDataObj(array(
//			'condition' => array(
//				'email' => $email
//			),
//			'count' => true
//		)));
//		
//		if($count == 0)$this->content= 'true';
//		else $this->content= 'false';
//	}
	
	public function AjaxRemoveUsersAction($param) {
		$this->setNoRender();
		
		$data = Request::GetAllPost();
		
		if(isset($data['ids']) && is_array($data['ids']) && !empty($data['ids'])) {
			$ids = implode(',',$data['ids']);
			$users = UserDAL::GetResult(UserDAL::GetDalDataObj(array(
				'condition' => array(
					'id_user' => array(
						'condition' => 'IN',
						'value' => "($ids)"
					)
				)
			)));
			
			foreach($users AS $user) {
				UserDAL::Delete($user->getDalDataObj());
			}
		}
	}
	
	public function RemoveUserAction($param)
	{
		$this->setNoRender();
		$users = UserDAL::GetResult(UserDAL::GetDalDataObj(array(
			'condition' => array(
				'id' => array(
					$param['id']
				)
			)
		)));	
		if(isset($users[0]))
		{
			$objs = UserExtendedProfileDAL::GetResult(UserExtendedProfileDAL::GetDalDataObj(array('condition'=>array('id_user'=>array($users[0]->getId())))));
			UserExtendedProfileDAL::Delete($objs[0]->getDalDataObj());
			
			
			UserDAL::Delete($users[0]->getDalDataObj());
		}
	}
	
	public function ToggleActivateAction($param)
	{
		$this->setNoRender();
		$users = UserDAL::GetResult(UserDAL::GetDalDataObj(array(
				'condition' => array(
					'id_user' => array(
						$param['id']
					)
				)
			)));
		if(isset($users[0]))
		{			
			if($users[0]->getActive() == 0)
			{
				$users[0]->setActive(1);
				// aktywacja usera - mail z wiadomoscia

			} else {
				$users[0]->setActive(0);
			}
			UserDAL::Update($users[0]->GetDalDataObj());
		}
		
	}
	
	public function ToggleStatusAction($param)
	{
		$this->setNoRender();
		UserDAL::DefaultToggleFieldById(UserDAL::GetDalDataObj(array('id' => $param['id'])), 'status');
	}
	
	/** ?? **/
	public function AjaxBlockUsersAction($param) {
		$this->setNoRender();
		
		$data = Request::GetAllPost();
		
		if(isset($data['ids']) && is_array($data['ids']) && !empty($data['ids'])) {
			$ids = implode(',',$data['ids']);
			$users = UserDAL::GetResult(UserDAL::GetDalDataObj(array(
				'condition' => array(
					'id_user' => array(
						'condition' => 'IN',
						'value' => "($ids)"
					)
				)
			)));
			
			foreach($users AS $user) {
				if(isset($data['block'])) {
					$user->setStatus(0);
				}else{
					$status = $user->getStatus()==1?0:1;
					$user->setStatus($status);
				}
				UserDAL::Update($user->getDalDataObj());
				
			}
		}
	}
	
	public function AjaxActiveUsersAction($param) {
		$this->setNoRender();
		
		$data = Request::GetAllPost();
		
		if(isset($data['ids']) && is_array($data['ids']) && !empty($data['ids'])) {
			$ids = implode(',',$data['ids']);
			$users = UserDAL::GetResult(UserDAL::GetDalDataObj(array(
				'condition' => array(
					'id_user' => array(
						'condition' => 'IN',
						'value' => "($ids)"
					)
				)
			)));
			
			foreach($users AS $user) {
				if(isset($data['block'])) {
					$user->setStatus(0);
				}else{
					$status = $user->getActive()==1?0:1;

					if($status == 0) {
						//TODO tutaj wysyłanie maila aktywacyjnego
					}
					
					$user->setActive($status);
				}
				UserDAL::Update($user->getDalDataObj());
				
			}
		}
	}
	
	public function EditUserAction($param) {
		$errors = array();
		$id = isset($param['id'])?$param['id']:0;
		$obj = UserDAL::GetResult(UserDAL::GetDalDataObj(array(
			'condition' => array(
				'id' => array($id)
			)
		)));
		if(empty($obj)) {
			$this->addRedirect(Router::GenerateUrl('User_Index',array('User' => 'Index')),0);
			return;
		}else{
			$obj = $obj[0];

			if(Request::IsPost()) {
				$data = Request::GetAllPost();
				
				if(isset($data['first_name']))
				{
					$obj->setFirstName($data['first_name']);
				}
				if(isset($data['last_name']))
				{
					$obj->setLastName($data['last_name']);
				}
				if(isset($data['status']))
				{
					$obj->setStatus($data['status']);
				}
				if(isset($data['active']))
				{
					$obj->setActive($data['active']);
				}
				
				if(isset($data['password']) && !empty($data['password']))
				{
					if(strlen($data['password']) > 4)
					{
						$obj->setPassword(UserDAL::GeneratePassword($data['password']));
					} else {
						if(!isset($errors['password'])) $errors['password'] = array();
						$errors['password'][] = 'Nowe hasło musi mieć więcej niż 4 znaki.';
					}
					
				}
				UserDAL::Save($obj->getDalDataObj());
			}

			$this->smarty->assign('user',$obj);
			$this->smarty->assign('errors', $errors);

		}
	}
}